import { Button, Space } from 'antd';
import React, { useEffect, useImperativeHandle, useRef, useState } from 'react';
import CursorManager from './lib/utils';
import "./lib/index.css";




/**
 * 富文本编辑器组件
 * 支持插入特殊标签并高亮显示,限制字数,自动计数等功能
 * 
 * @component
 * @param {object} props
 * @param {object} props.form - antd Form 实例,用于表单数据管理
 * @param {function} props.onRef - 父组件获取编辑器实例的回调函数
 * 
 * @example
 * <RichTextEditor 
 *   form={form}
 *   onRef={ref => this.editor = ref}
 * />
 * 
 * 功能特性:
 * - 支持插入 #客户姓名#、#客服姓名#、#客服加友链接# 等特殊标签
 * - 标签以高亮样式显示且不可编辑
 * - 限制总字数160字,超出显示提示
 * - 实时显示已输入/剩余字数
 * - 支持通过 ref 获取编辑器文本内容
 */
const RichTextEditor = ({ form, onRef, maxLength = 160 }) => {
    const editorRef = useRef(null);
    const [isExceeded, setIsExceeded] = useState(false);
    const [length, setlength] = useState(0);
    useEffect(() => {
        if (length > maxLength) {
            setIsExceeded(true);
        } else {
            setIsExceeded(false);
        }
    }, [length, maxLength])

    // 高亮标记文本
    const highlightTags = (html) => {
        if (!html) return '';
        return html.replace(/#[^#]+#/g, match =>
            `<span class="highlight-tag" data-tag="${match}">${match}</span>`
        );
    };





    const insertTag = (tagName) => {
        const editor = editorRef.current;
        if (!editor) return;

        // 确保编辑器获得焦点
        if (!editor.contains(document.activeElement)) {
            editor.focus();
        }

        // 1. 保存当前光标位置
        const savedPos = CursorManager.savePosition(editor);

        // 2. 创建标签元素
        const tag = document.createElement('span');
        tag.className = 'highlight-tag uneditable-tag';
        tag.contentEditable = 'false';
        tag.textContent = `#${tagName}#`;
        tag.dataset.tag = tagName;

        // 3. 插入标签
        const selection = window.getSelection();
        if (selection.rangeCount) {
            const range = selection.getRangeAt(0);
            range.deleteContents();
            range.insertNode(tag);

            // 4. 更新表单值
            updateFormValue();

            // 5. 恢复光标位置
            CursorManager.restorePosition(editor, {
                ...savedPos,
                charsBefore: savedPos.charsBefore + tag.textContent.length
            });
        } else {

        }
    };



    const updateFormValue = () => {
        const editor = editorRef.current;
        if (!editor) return;


        // 获取纯文本内容（保留标签标记）
        let plainText = '';
        const walker = document.createTreeWalker(
            editor,
            NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT,
            null,
            false
        );

        while (walker.nextNode()) {
            const node = walker.currentNode;
            if (node.nodeType === Node.TEXT_NODE) {
                plainText += node.textContent;
            } else if (node.classList.contains('highlight-tag')) {
                plainText += node.textContent;
            }
        }

        setlength(editorRef.current.innerText.length);
    };

    const handleEditorClick = (e) => {
        // 确保点击在编辑器内部
        if (!editorRef.current.contains(e.target)) {
            editorRef.current.focus();
        }
    };

    const handleKeyDown = (e) => {

        if (e.key === 'Backspace' || e.key === 'Delete') {
            const selection = window.getSelection();
            if (!selection.rangeCount) return;

            const range = selection.getRangeAt(0);
            const parent = range.startContainer.parentElement;

            // 防止删除标签
            if (parent.classList.contains('highlight-tag')) {
                e.preventDefault();

                // 将光标移动到标签后面
                const newRange = document.createRange();
                newRange.setStartAfter(parent);
                newRange.collapse(true);
                selection.removeAllRanges();
                selection.addRange(newRange);
            }
        }
    };



    useImperativeHandle(onRef, () => {
        return {
            getText: () => {
                return editorRef.current.innerText;
            }
        }
    })
    return (
        <>
            <div className='editor-reatch'>
                <div
                    ref={editorRef}

                    contentEditable
                    className="custom-rich-textarea"
                    placeholder="输入短信模板"
                    // onInput={handleInput}
                    // onKeyDown={handleKeyDown}
                    // onClick={handleClick}  // 添加点击事件
                    // onCompositionStart={handleCompositionStart}
                    // onCompositionEnd={handleCompositionEnd}
                    onInput={updateFormValue}
                    onClick={handleEditorClick}
                    onKeyDown={handleKeyDown}
                    dangerouslySetInnerHTML={{
                        __html: highlightTags(form.getFieldValue('smsContext') || ''),
                    }}
                    maxLength={160}
                    style={{
                        minHeight: '80px',
                        border: '1px solid #d9d9d9',
                        borderRadius: '2px',
                        padding: '4px 11px',
                        whiteSpace: 'pre-wrap',
                    }}
                />
                <div className='action' style={{
                    padding: "5px 0px;"
                }}>
                    <div className='action-content' style={{
                        padding: "5px 0px",
                    }}>
                        <Space>
                            <Button size="small" type="dashed" className="btn" onClick={() => insertTag('客户姓名')}>插入客户姓名</Button>
                            <Button size="small" type="dashed" className="btn" onClick={() => insertTag('客服姓名')}>插入客服姓名</Button>
                            <Button size="small" type="dashed" className="btn" onClick={() => insertTag('客服加友链接')}>插入客服加友链接</Button>
                            <div style={{
                                textAlign: 'right',
                                color: isExceeded ? '#ff4d4f' : 'inherit'
                            }}>
                                已输入: {length} / 剩余: {160 - length}
                                {isExceeded && <span style={{ marginLeft: 8 }}>已超出限制!</span>}
                            </div>
                        </Space>
                        <div ></div>
                    </div>
                </div>
            </div>
        </>

    );
};

export default RichTextEditor;

